<?php

class Ead_RepositorioController extends Ead_Controller_Action
{
    private $_table     = 'TOPICO';
    private $_pk        = 'TPC_ID';
    private $_order_col = 'TPC_ORD';
    private $_order     = 'ASC';
    private $_sta_col   = 'TPC_STA';
    private $obj        = '';
    private $form       = '';
    
    public  $dir        = 'public/upload/repositorio/';
    public  $_file_col  = 'arquivo';
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Sistema_Form_Topicoead();       
    }

    public function indexAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/ead/repositorio.js?1=6');

        //monta menu
        $sessao = new Zend_Session_Namespace('Professor');
        
        $query = 'SELECT SQL_CACHE DISTINCT p.PRS_ID, p.PRS_NOM, d.DCP_ID, d.DCP_NOM '
                .' FROM PROFESSOR p, DISCIPLINA d'
                .' WHERE p.DCP_ID = d.DCP_ID AND p.PRS_STA = 1 AND d.DCP_STA = 1'
                .' AND p.PRS_ID = '.$sessao->professor['PRS_ID']
                .' ORDER BY PRS_NOM';
        $result = $this->db->fetchAll($query); 
        $this->view->menu = $result;
        
        $this->view->PRS_ID = $sessao->professor['PRS_ID'];
        
        $where = '';
        $dcp_id = $this->_getParam('dcp_id', 0);
        if($dcp_id > 0){ 
            $where = ' AND DCP_ID = '.$dcp_id.' ';
        } else if($result[0]['DCP_ID'] > 0){     
            $where = ' AND DCP_ID = '.$result[0]['DCP_ID'].' ';
        }
        $query = 'SELECT SQL_CACHE DISTINCT DCP_NOM FROM DISCIPLINA WHERE DCP_STA = 1 '. $where;
        $result = $this->db->fetchRow($query); 
        $this->view->dis = $result; 
        //monta menu  
        
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('imagem','library');
        Zend_Loader::loadClass('dominio','library');
        
        $query = 'SELECT SQL_CACHE t.* '
                .' FROM TOPICO t, PROFESSOR p '
                .' WHERE t.PRS_ID = p.PRS_ID AND p.PRS_ID = '.$sessao->professor['PRS_ID']
                .' AND t.TPC_STA = 1 AND p.PRS_STA = 1 '
                . $where 
                .' ORDER BY TPC_ORD';
        $result = $this->db->fetchAll($query); 
        $this->view->topicos = $result;
        
    }
    
    
    public function editAction() {
        
        //monta menu
        $sessao = new Zend_Session_Namespace('Professor');
        
        $query = 'SELECT SQL_CACHE DISTINCT p.PRS_ID, p.PRS_NOM, d.DCP_ID, d.DCP_NOM '
                .' FROM PROFESSOR p, DISCIPLINA d'
                .' WHERE p.DCP_ID = d.DCP_ID AND p.PRS_STA = 1 AND d.DCP_STA = 1'
                .' AND p.PRS_ID = '.$sessao->professor['PRS_ID']
                .' ORDER BY PRS_NOM';
        $result = $this->db->fetchAll($query); 
        $this->view->menu = $result;
        
        $this->view->PRS_ID = $sessao->professor['PRS_ID'];
        
        $where = '';
        $dcp_id = $this->_getParam('dcp_id', 0);
        if($dcp_id > 0){ 
            $where = ' AND DCP_ID = '.$dcp_id.' ';
        } else if($result[0]['DCP_ID'] > 0){     
            $where = ' AND DCP_ID = '.$result[0]['DCP_ID'].' ';
        }
        $query = 'SELECT SQL_CACHE DISTINCT DCP_NOM FROM DISCIPLINA WHERE DCP_STA = 1 '. $where;
        $result = $this->db->fetchRow($query); 
        $this->view->dis = $result; 
        //monta menu   
        
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('tools','library');
        
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        
        $this->form->setDefault('PRS_ID', $sessao->professor['PRS_ID']);           
        $this->view->form = $this->form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if($this->form->isValid($formData)) {
                    $id = (int) $formData[$this->_pk]; //$this->form->getValue($this->_pk);

                    $data = $formData;//$this->form->getValues();
                    unset($data['Salvar']);
                   
                    $this->db->beginTransaction();
                    if ($id == 0){
                        $data['PRS_ID'] = $sessao->professor['PRS_ID'];
                        $data['TPC_DAT'] = date('Y-m-d');
                        $data['TPC_HOR'] = date('H:i:00');
                        $data['TPC_STA'] = 1;
                        $data[$this->_order_col] = tools::returnOrdMax($this->_table, $this->_order_col);
                        $this->db->insert($this->_table,$data);
                    }else{                      
                        $this->db->update($this->_table,$data, $this->_pk.' = ' . $id);
                    }
                    
                    $this->db->commit();
                    
                    $this->_helper->redirector('index');      
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
                $this->db->rollBack();
            }  
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk .' = ' . $id;
                $data = $this->db->fetchRow($query);
                $this->form->populate($data);   
            }
        }
    }
    
    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $id = $this->_getParam('id', 0);
        if((int) $id > 0 ) {   
            $this->db->beginTransaction();
            try {
                $ok = (bool) $this->db->delete($this->_table, $this->_pk . ' = ' . $id);
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = 'Não é possível excluir o tópico porque possui conteúdos cadastrados!';
                $this->db->rollBack();
            }          
        }     
        echo json_encode(array('ok' => $ok, 'msg'=> $msg));
    } 
    
    public function conteudoAction() {
        
        //monta menu
        $sessao = new Zend_Session_Namespace('Professor');
        
        $query = 'SELECT SQL_CACHE DISTINCT p.PRS_ID, p.PRS_NOM, d.DCP_ID, d.DCP_NOM '
                .' FROM PROFESSOR p, DISCIPLINA d'
                .' WHERE p.DCP_ID = d.DCP_ID AND p.PRS_STA = 1 AND d.DCP_STA = 1'
                .' AND p.PRS_ID = '.$sessao->professor['PRS_ID']
                .' ORDER BY PRS_NOM';
        $result = $this->db->fetchAll($query); 
        $this->view->menu = $result;
        
        $this->view->PRS_ID = $sessao->professor['PRS_ID'];
        
        $where = '';
        $dcp_id = $this->_getParam('dcp_id', 0);
        if($dcp_id > 0){ 
            $where = ' AND DCP_ID = '.$dcp_id.' ';
        } else if($result[0]['DCP_ID'] > 0){     
            $where = ' AND DCP_ID = '.$result[0]['DCP_ID'].' ';
        }
        $query = 'SELECT SQL_CACHE DISTINCT DCP_NOM FROM DISCIPLINA WHERE DCP_STA = 1 '. $where;
        $result = $this->db->fetchRow($query); 
        $this->view->dis = $result; 
        //monta menu   
        
        Zend_Loader::loadClass('datetools','library');
                
        $tpc_id = $this->_getParam('tpc_id', 0);
        
        $query = 'SELECT SQL_CACHE * FROM CONTEUDO WHERE TPC_ID = '.$tpc_id.' AND CON_STA = 1 ORDER BY CON_ORD';
        $result = $this->db->fetchAll($query); 
        $this->view->conteudos = $result;
    
        
    }
    
    public function editconteudoAction() {
        
        //monta menu
        $sessao = new Zend_Session_Namespace('Professor');
        
        $query = 'SELECT SQL_CACHE DISTINCT p.PRS_ID, p.PRS_NOM, d.DCP_ID, d.DCP_NOM '
                .' FROM PROFESSOR p, DISCIPLINA d'
                .' WHERE p.DCP_ID = d.DCP_ID AND p.PRS_STA = 1 AND d.DCP_STA = 1'
                .' AND p.PRS_ID = '.$sessao->professor['PRS_ID']
                .' ORDER BY PRS_NOM';
        $result = $this->db->fetchAll($query); 
        $this->view->menu = $result;
        
        $this->view->PRS_ID = $sessao->professor['PRS_ID'];
        
        $where = '';
        $dcp_id = $this->_getParam('dcp_id', 0);
        if($dcp_id > 0){ 
            $where = ' AND DCP_ID = '.$dcp_id.' ';
        } else if($result[0]['DCP_ID'] > 0){     
            $where = ' AND DCP_ID = '.$result[0]['DCP_ID'].' ';
        }
        $query = 'SELECT SQL_CACHE DISTINCT DCP_NOM FROM DISCIPLINA WHERE DCP_STA = 1 '. $where;
        $result = $this->db->fetchRow($query); 
        $this->view->dis = $result; 
        //monta menu   
        
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('imagem','library');
        Zend_Loader::loadClass('tools','library');
        
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        
        $this->dir = 'public/upload/conteudo/';
        $this->_file_col  = 'CON_FILE';
        $this->form = new Sistema_Form_Conteudoead();
        
        $tpc_id = $this->_getParam('tpc_id', 0);
        $this->form->TPC_ID->setValue($tpc_id);
        
        $this->view->form = $this->form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if($this->form->isValid($formData)) {
                    
                    $id = (int) $this->form->getValue('CON_ID');
                    
                    $returnImg = imagem::upload($this->_file_col,$this->dir,$id);
                    
                    $data = $this->form->getValues();
                    
                    unset($data['Salvar']);
                    unset($data['img']);
                    unset($data[$this->_file_col]);
                    
                    // material
                    $data['TIP_ID'] = 2;
                    if($returnImg['filenew']){
                        $ext = strtolower(end(explode('.', $returnImg['filenew'])));
                        if($ext == 'mp4') $data['TIP_ID'] = 1;
                        else $data['TIP_ID'] = 2;
                    }
                    
                    $datahora = date('Y-m-d H:i:00'); 
                    
                    //$this->db->beginTransaction();
                    if ($id == 0){
                        $data['TPC_ID'] = $tpc_id;
                        $data['CON_DATHOR'] = $datahora;
                        $data['CON_STA'] = 1;
                        $data['CON_ORD'] = tools::returnOrdMax('CONTEUDO', 'CON_ORD', ' TPC_ID = '.$tpc_id);
                        $this->db->insert('CONTEUDO',$data);
                        $id = $this->db->lastInsertId();
                    
                    }else{            
                        
                        if(strlen($returnImg['filenew']) > 0) $data['CON_DATHOR'] = $datahora;
                        
                        $this->db->update('CONTEUDO',$data, 'CON_ID = ' . $id);
                    }
                    
                    if(strlen($returnImg['filenew']) > 0){
                                              
                        $_id = imagem::formatNomeArquivo($id,$datahora);

                        imagem::rename($_id,$this->dir,$returnImg['filenew']);

                        chmod($this->dir.$_id.'.'.$ext, 0644);
                    }
                    
                    //$this->db->commit();
                    
                    $urlOptions = array('controller'=>$this->_controller,'action'=>'conteudo','tpc_id'=>$tpc_id);
                    $this->_helper->redirector->gotoRoute($urlOptions);    
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
                //$this->db->rollBack();
            }  
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $query = 'SELECT SQL_CACHE * FROM CONTEUDO WHERE CON_ID = ' . $id;
                $data = $this->db->fetchRow($query);
                $this->form->populate($data);   
            }
        }
    }
    
    public function deleteconteudoAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $id = $this->_getParam('id', 0);
        Zend_Loader::loadClass('imagem','library');
        $this->dir = 'public/upload/conteudo/';
        if((int) $id > 0 ) {   
            $this->db->beginTransaction();
            try {
                
                imagem::delete($this->getNomeArquivo($id),$this->dir);
                
                $ok = (bool) $this->db->delete('CONTEUDO', 'CON_ID = ' . $id);
                
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = 'Não é possível excluir o conteúdo porque já foi enviado aos alunos!';
                $this->db->rollBack();
            }          
        }     
        echo json_encode(array('ok' => $ok, 'msg'=> $msg));
    }
    
    public function getNomeArquivo($id) {
        Zend_Loader::loadClass('imagem','library');
        
        $query = 'SELECT SQL_CACHE CON_ID,CON_DATHOR FROM CONTEUDO WHERE CON_ID = ' . $id;
        $res = $this->db->fetchRow($query);
        
        return  imagem::formatNomeArquivo($res['CON_ID'],$res['CON_DATHOR']);
    }
    
    public function orderAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender(); 
        
        $sessao = new Zend_Session_Namespace('Professor');
        
        $id = $this->_getParam('id', 0);
        $ord = $this->_getParam('ord', 0);
        $pos = $this->_getParam('pos', 0);
        
        if($id > 0 && $pos == 0)
        {
            
            $query = 'SELECT SQL_CACHE TPC_ID,TPC_ORD FROM TOPICO  '
                .' WHERE PRS_ID = '.$sessao->professor['PRS_ID'].' AND TPC_STA = 1 '
                .' AND TPC_ORD < '.$ord 
                .' ORDER BY TPC_ORD DESC LIMIT 1';
            $result = $this->db->fetchAll($query); 
            foreach($result as $row){
                $data= array('TPC_ORD' => $ord);
                $this->db->update('TOPICO',$data, 'TPC_ID = '.$row['TPC_ID'] );
                $ord = $row['TPC_ORD'];
            }
            
            $data= array('TPC_ORD' => $ord );
            $this->db->update('TOPICO',$data, 'TPC_ID = ' . $id);
            
        } else if($id > 0 && $pos == 1) {
            
            $query = 'SELECT SQL_CACHE TPC_ID,TPC_ORD FROM TOPICO  '
                .' WHERE PRS_ID = '.$sessao->professor['PRS_ID'].' AND TPC_STA = 1 '
                .' AND TPC_ORD > '.$ord 
                .' ORDER BY TPC_ORD ASC LIMIT 1';
            $result = $this->db->fetchAll($query); 
            foreach($result as $row){
                $data= array('TPC_ORD' => $ord);
                $this->db->update('TOPICO',$data, 'TPC_ID = '.$row['TPC_ID'] );
                $ord = $row['TPC_ORD'];
            }
            
            $data= array('TPC_ORD' => $ord );
            $this->db->update('TOPICO',$data, 'TPC_ID = ' . $id);    
        }
        
        $this->_helper->redirector('index'); 
    }
    
    public function orderconteudoAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender(); 
        
        $id = $this->_getParam('id', 0);
        $ord = $this->_getParam('ord', 0);
        $pos = $this->_getParam('pos', 0);
        $tpc_id = $this->_getParam('tpc_id', 0);
        $rtn = $this->_getParam('rtn', 'conteudo');
        
        if($id > 0 && $pos == 0 && $tpc_id > 0)
        {
            
            $query = 'SELECT SQL_CACHE CON_ID,CON_ORD FROM CONTEUDO  '
                .' WHERE TPC_ID = '.$tpc_id.' AND CON_STA = 1 '
                .' AND CON_ORD < '.$ord 
                .' ORDER BY CON_ORD DESC LIMIT 1';
            $result = $this->db->fetchAll($query); 
            foreach($result as $row){
                $data= array('CON_ORD' => $ord);
                $this->db->update('CONTEUDO',$data, 'CON_ID = '.$row['CON_ID'] );
                $ord = $row['CON_ORD'];
            }
            
            $data= array('CON_ORD' => $ord );
            $this->db->update('CONTEUDO',$data, 'CON_ID = ' . $id);
            
        } else if($id > 0 && $pos == 1 && $tpc_id > 0) {
            
            $query = 'SELECT SQL_CACHE CON_ID,CON_ORD FROM CONTEUDO  '
                .' WHERE TPC_ID = '.$tpc_id.' AND CON_STA = 1 '
                .' AND CON_ORD > '.$ord 
                .' ORDER BY CON_ORD ASC LIMIT 1';
            $result = $this->db->fetchAll($query); 
            foreach($result as $row){
                $data= array('CON_ORD' => $ord);
                $this->db->update('CONTEUDO',$data, 'CON_ID = '.$row['CON_ID'] );
                $ord = $row['CON_ORD'];
            }
            
            $data= array('CON_ORD' => $ord );
            $this->db->update('CONTEUDO',$data, 'CON_ID = ' . $id);    
        }
        
        $urlOptions = array('controller'=>$this->_controller,'action'=>$rtn,'tpc_id'=>$tpc_id);
        $this->_helper->redirector->gotoRoute($urlOptions);
    }
}